<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理系统</title>
    <!-- 网站图标 -->
    <link rel="icon" type="image/svg+xml" href="static/images/favicon.svg">
    <link rel="alternate icon" type="image/x-icon" href="static/images/favicon.ico">
    <!-- 引入本地的 Bootstrap CSS -->
    <link rel="stylesheet" href="static/css/bootstrap.min.css">
    <!-- 引入本地的自定义 CSS -->
    <link rel="stylesheet" href="static/css/styles.css">
    <!-- jQuery -->
    <script src="static/js/jquery.min.js"></script>
    <!-- Bootstrap JS (使用bundle版本，包含Popper.js，这是下拉菜单功能正常工作的必要条件) -->
    <script src="static/js/bootstrap.bundle.min.js"></script>
    <!-- 手动处理下拉菜单的脚本 -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM加载完成，初始化下拉菜单脚本');
            
            // 为下拉按钮添加点击事件
            const dropdownBtn = document.getElementById('userDropdown');
            console.log('下拉按钮元素:', dropdownBtn);
            
            if (dropdownBtn) {
                dropdownBtn.addEventListener('click', function(e) {
                    console.log('下拉按钮被点击');
                    // 查找对应的下拉菜单
                    const dropdownMenu = this.nextElementSibling;
                    console.log('找到的下拉菜单:', dropdownMenu);
                    
                    if (dropdownMenu && dropdownMenu.classList.contains('dropdown-menu')) {
                        // 切换显示/隐藏状态
                        dropdownMenu.classList.toggle('show');
                        console.log('下拉菜单显示状态切换后:', dropdownMenu.classList.contains('show'));
                    }
                });
                
                // 点击其他地方关闭下拉菜单
                document.addEventListener('click', function(e) {
                    if (e.target !== dropdownBtn && !dropdownBtn.contains(e.target)) {
                        const dropdownMenus = document.querySelectorAll('.dropdown-menu.show');
                        dropdownMenus.forEach(menu => {
                            menu.classList.remove('show');
                            console.log('下拉菜单已关闭');
                        });
                    }
                });
            }
        });
    </script>
    <!-- 引入语言包 -->
    <script src="static/js/translations.js"></script>
    <!-- 引入模块加载器 -->
    <script src="static/js/module-loader.js"></script>
</head>
<body>
    <!-- 标题栏 - 位于顶部，占满整个宽度 -->
    <header class="header-bar">
        <div class="header-content">
            <div class="header-left">
                <h1 class="header-title">商品管理系统</h1>
            </div>
            <div class="header-right">
                
                <div class="language-switch mr-3">
                    <button id="lang-zh" class="btn btn-outline-light btn-sm active">汉文</button>
                    <button id="lang-uy" class="btn btn-outline-light btn-sm">ئۇيغۇرچە</button> 
                </div>
                
                <!-- 用户下拉菜单 -->
                <div class="dropdown mr-3">
                    <button class="btn btn-outline-light btn-sm dropdown-toggle" type="button" id="userDropdown">
                        <span>欢迎, {{ username }}</span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="#" id="changePasswordLink">修改密码</a></li>
                        <li><a class="dropdown-item" href="/logout">退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </header>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="sidebar sidebar-left">
                <div class="sidebar-sticky">
                    <!-- Logo -->
                    <div class="text-center mt-3">
                        <img src="static/images/logo.jpeg" alt="Logo" class="logo">
                    </div>
                    <!-- 系统版本 -->
                    <h5 class="text-center mt-3 system-version">{{ system_version }}</h5>
                    <h4 class="text-center mt-2 store-name">商店名称</h4>
                    <!-- 菜单项 -->
                    <ul class="nav flex-column parent-menu">
                        <li class="nav-item parent-item">
                            <a class="nav-link parent-link active" href="#" data-target="settle" data-translate="settle">
                                结算管理
                                <span class="menu-toggle">▼</span>
                            </a>
                            <ul class="sub-menu expanded">
                                <li class="nav-item">
                                    <a class="nav-link" href="#" data-target="settle_item" data-translate="settle_item">商品结算</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#" data-target="settle_detail" data-translate="settle_detail">结算明细</a>
                                </li>
                            </ul>
                        </li>
                        <li class="nav-item parent-item">
                            <a class="nav-link parent-link" href="#" data-target="products" data-translate="products">
                                商品管理
                                <span class="menu-toggle">▼</span>
                            </a>
                            <ul class="sub-menu">
                                <li class="nav-item">
                                    <a class="nav-link" href="#" data-target="add" data-translate="add">商品管理</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#" data-target="warning" data-translate="warning">库存警告</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#" data-target="expiry_warning" data-translate="expiry_warning">近效期警告</a>
                                </li>
                            </ul>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-target="settings" data-translate="settings">系统设置</a>
                        </li>
                    </ul>
                    
                    <!-- 原生父子菜单CSS -->
                    <style>
                        /* 父菜单项样式 */
                        .parent-item {
                            position: relative;
                        }
                        
                        .parent-link {
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                        }
                        
                        /* 菜单切换图标 */
                        .menu-toggle {
                            font-size: 12px;
                            transition: transform 0.3s ease;
                        }
                        
                        .parent-link.active .menu-toggle {
                            transform: rotate(180deg);
                        }
                        
                        /* 子菜单样式 */
                        .sub-menu {
                            list-style: none;
                            padding-left: 0;
                            margin: 0;
                            max-height: 0;
                            overflow: hidden;
                            transition: max-height 0.3s ease;
                            background-color: #343a40; /* 深色背景 */
                        }
                        
                        .sub-menu.expanded {
                            max-height: 200px;
                        }
                        
                        /* 子菜单项样式 */
                        .sub-menu .nav-item .nav-link {
                            padding-left: 25px;
                            font-size: 14px;
                            border-left: 3px solid transparent;
                            color: #ffffff; /* 白色字体，确保与深色背景有足够对比度 */
                        }
                        
                        .sub-menu .nav-item .nav-link:hover {
                            background-color: #495057;
                            border-left-color: #0d6efd;
                            color: #ffffff;
                        }
                        
                        .sub-menu .nav-item .nav-link.active {
                            border-left-color: #0d6efd;
                            background-color: #495057;
                            color: #ffffff;
                        }
                    </style>
                    
                    <!-- 原生父子菜单JavaScript -->
                    <script>
                        document.addEventListener('DOMContentLoaded', function() {
                            // 为所有父菜单项添加点击事件
                            const parentLinks = document.querySelectorAll('.parent-link');
                            const subMenus = document.querySelectorAll('.sub-menu');
                            
                            parentLinks.forEach(link => {
                                link.addEventListener('click', function(e) {
                                    // 阻止默认行为
                                    e.preventDefault();
                                    
                                    const subMenu = this.nextElementSibling;
                                    const isExpanded = subMenu.classList.contains('expanded');
                                    
                                    // 收起所有其他展开的子菜单
                                    subMenus.forEach(menu => {
                                        if (menu !== subMenu) {
                                            menu.classList.remove('expanded');
                                            menu.previousElementSibling.classList.remove('active');
                                        }
                                    });
                                    
                                    // 切换当前子菜单的展开状态
                                    subMenu.classList.toggle('expanded', !isExpanded);
                                    
                                    // 更新父菜单项的激活状态
                                    this.classList.toggle('active', !isExpanded);
                                });
                            });
                            
                            // 为子菜单项添加点击事件
                            const subMenuLinks = document.querySelectorAll('.sub-menu .nav-link');
                            
                            subMenuLinks.forEach(link => {
                                link.addEventListener('click', function() {
                                    // 确保父菜单展开
                                    const subMenu = this.closest('.sub-menu');
                                    const parentLink = subMenu.previousElementSibling;
                                    
                                    // 收起所有其他子菜单
                                    subMenus.forEach(menu => {
                                        if (menu !== subMenu) {
                                            menu.classList.remove('expanded');
                                            menu.previousElementSibling.classList.remove('active');
                                        }
                                    });
                                    
                                    // 确保当前子菜单展开
                                    subMenu.classList.add('expanded');
                                    parentLink.classList.add('active');
                                });
                            });
                        });
                    </script>
                </div>
            </div>

            <!-- 主内容区域 -->
            <div class="main-content main-content-left">
                <!-- 导航栏 -->
                <nav class="navbar navbar-expand-lg navbar-dark bg-custom d-none" id="mainNavbar">
                    <div class="container-fluid">
                        <div id="module-name" class="module-title">当前模块：欢迎使用</div>
                    </div>
                </nav>

                <!-- 欢迎界面 -->
                <div id="welcome" class="card-content h-100 d-flex flex-column align-items-center justify-content-center">
                    <div class="text-center" style="max-width: 600px; padding: 40px; background-color: #f8f9fa; border-radius: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
                        <!-- 系统统计信息卡片 -->
                        <div class="system-stats mb-4" style="text-align: left;">
                            <h4 id="systemStatsTitle" data-translate="system_stats_title" style="margin-bottom: 15px; color: #6c757d; border-bottom: 1px solid #dee2e6; padding-bottom: 8px;">系统统计信息</h4>
                            <div class="stats-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                <div class="stat-item p-3 bg-white rounded shadow-sm">
                                    <div class="stat-label" id="totalProductsLabel" data-translate="total_products">商品总数</div>
                                    <div class="stat-value" id="totalProductsValue" style="font-size: 24px; font-weight: bold; color: #007bff;">-</div>
                                </div>
                                <div class="stat-item p-3 bg-white rounded shadow-sm">
                                    <div class="stat-label" id="warningProductsLabel" data-translate="warning_products">库存警告</div>
                                    <div class="stat-value" id="warningProductsValue" style="font-size: 24px; font-weight: bold; color: #ffc107;">-</div>
                                </div>
                                <div class="stat-item p-3 bg-white rounded shadow-sm">
                                    <div class="stat-label" id="outOfStockLabel" data-translate="out_of_stock">库存为零</div>
                                    <div class="stat-value" id="outOfStockValue" style="font-size: 24px; font-weight: bold; color: #dc3545;">-</div>
                                </div>
                                <div class="stat-item p-3 bg-white rounded shadow-sm">
                                    <div class="stat-label" id="todayTransactionsLabel" data-translate="today_transactions">今日交易</div>
                                    <div class="stat-value" id="todayTransactionsValue" style="font-size: 24px; font-weight: bold; color: #28a745;">-</div>
                                </div>
                                <div class="stat-item p-3 bg-white rounded shadow-sm">
                                    <div class="stat-label" id="todayTransactionAmountLabel" data-translate="transaction_amount">交易金额</div>
                                    <div class="stat-value" id="todayTransactionAmountValue" style="font-size: 24px; font-weight: bold; color: #17a2b8;">-</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-center">
                            <a href="#" data-target="settle_item" class="btn btn-primary btn-lg" id="startSettlementBtn">
                                    <i class="fas fa-shopping-cart"></i> <span id="startSettlementText" data-translate="start_settlement">开始商品结算</span>
                                </a>
                        </div>
                    </div>
                </div>

                <!-- 商品结算界面 -->
                <div id="settle_item" class="card-content h-100 d-flex flex-column d-none">
    
                    <div class="form-group" style="width: 100%;">
                        <!-- <label for="barcode">商品条码</label> -->
                        <input type="text" id="barcode" class="form-control" placeholder="扫码或手动输入条码" style="height: 50px; font-size: 18px;" autocomplete="off" pattern="[0-9]{13}" maxlength="13" title="请输入13位数字商品条码">
                    </div>
                    
                    <!-- 可滚动的购物车清单区域 -->
                    <div id="productList" class="mt-3 flex-grow-1 overflow-auto" style="max-height: calc(100vh - 250px);width: 100%;">
                        <h4 data-translate="shopping_cart" style="font-size: 20px; font-weight: bold;">购物车</h4>
                        <table class="table table-bordered" style="font-size: 16px;">
                            <thead style="position: sticky; top: 0; background-color: #f8f9fa; z-index: 10;">
                                <tr style="height: 50px;">
                                    <th style="vertical-align: middle;" data-translate="product_name">商品名称</th>
                                    <th style="vertical-align: middle;" data-translate="unit_price">单价</th>
                                    <th style="vertical-align: middle;" data-translate="unit">单位</th>
                                    <th style="vertical-align: middle;" data-translate="quantity">数量</th>
                                    <th style="vertical-align: middle;" data-translate="price">价格</th>
                                    <th style="vertical-align: middle;" data-translate="action">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 商品清单动态生成 -->
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 固定在底部的合计和操作按钮 -->
                    <div class="mt-3 d-flex justify-content-between align-items-center bg-white p-4 border-top" style="position: sticky; bottom: 0; padding-top: 15px !important;width: 100%;">
                        <span data-translate="total_price" style="font-size: 20px; font-weight: bold; color: brown;">合计: <span id="totalPrice">0</span>元</span>
                        <div>
                            <button id="clearAll" class="btn btn-danger" data-translate="clear_all" style="padding: 10px 20px; font-size: 16px;">一键清零</button>
                            <button id="settleBill" class="btn btn-success ml-2" data-translate="settle_bill" style="padding: 10px 20px; font-size: 16px;">结算</button>
                        </div>
                    </div>
                </div>

                <!-- 结算明细界面 -->
                <div id="settle_detail" class="card-content d-none">
                    <div class="mb-4">
                        <h4 id="transactionRecordsTitle" data-translate="transaction_records">结算记录</h4>
                    </div>
                    
                    <!-- 搜索框 -->
                    <div class="mb-4 d-flex justify-content-start">
                        <input type="text" id="transactionNoSearch" class="form-control" data-translate-placeholder="search_transaction_no" placeholder="输入流水号查询" style="width: 300px;">
                        <button id="searchTransactionBtn" class="btn btn-primary ml-2" data-translate="search">查询</button>
                        <button id="resetSearchBtn" class="btn btn-secondary ml-2" data-translate="reset">重置</button>
                    </div>
                    
                    <!-- 结算记录表格 -->
                    <div class="table-responsive">
                        <table class="table table-bordered" style="font-size: 16px;">
                            <thead class="thead-dark">
                                <tr>
                                    <th id="transactionNoHeader" data-translate="transaction_no">流水号</th>
                                    <th id="transactionTimeHeader" data-translate="transaction_time">交易时间</th>
                                    <th id="totalAmountHeader" data-translate="total_amount">总金额</th>
                                    <th id="operationHeader" data-translate="operation">操作</th>
                                </tr>
                            </thead>
                            <tbody id="transactionTableBody">
                                <!-- 交易记录将通过JavaScript动态添加 -->
                                <tr>
                                    <td colspan="4" class="text-center" data-translate="no_records">暂无记录</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页控件 -->
                    <div class="mt-4 d-flex justify-content-between align-items-center">
                        <div id="paginationInfo" data-translate="pagination_info">显示 1-0 条，共 0 条</div>
                        <nav aria-label="Page navigation">
                            <ul class="pagination" id="paginationControls">
                                <!-- 分页控件将通过JavaScript动态添加 -->
                            </ul>
                        </nav>
                    </div>
                </div>
                
                <!-- 新增商品界面 -->
                <div id="add" class="card-content d-none">
                    <form id="productForm">
                        <div class="form-group" style="width: 100%;">
                            <label for="productBarcode" data-translate="product_barcode">商品条码</label>
                            <input type="text" id="productBarcode" class="form-control" required autocomplete="off" pattern="[0-9]{13}" maxlength="13" data-translate-title="enter_13_digit_barcode" title="请输入13位数字商品条码">
                        </div>
                        <div class="form-group">
                            <label for="productName" data-translate="product_name">商品名称</label>
                            <input type="text" id="productName" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label for="productPrice" data-translate="product_price">商品价格</label>
                            <input type="text" id="productPrice" class="form-control" required data-translate-placeholder="example_price" placeholder="例如: 2.5">
                        </div>
                        <div class="form-group">
                            <label for="productUnit" data-translate="product_unit">商品单位</label>
                            <input type="text" id="productUnit" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label for="productStock" data-translate="stock_quantity">库存数量</label>
                            <input type="number" id="productStock" class="form-control" required="">
                        </div>
                        <div class="form-group">
                            <label for="productExpiryDate" data-translate="expiry_date">失效期</label>
                            <input type="date" id="productExpiryDate" class="form-control">
                        </div>
                        <button type="submit" class="btn btn-primary" data-translate="add_product">添加商品</button>
                        <button type="submit" id="updateProduct" class="btn btn-primary" style="display: none;" data-translate="save_changes">保存修改</button>
                    </form>
                </div>

                <!-- 库存警告界面 -->
                <div id="warning" class="card-content d-none">
                    <h4 data-translate="stock_warning">库存警告</h4>
                    <div class="table-responsive">
                        <table id="warningTable" class="table table-striped">
                            <thead>
                                <tr>
                                    <th data-translate="product_barcode">商品条码</th>
                                    <th data-translate="product_name">商品名称</th>
                                    <th data-translate="unit_price">单价</th>
                                    <th data-translate="unit">单位</th>
                                    <th data-translate="stock_quantity">库存数量</th>
                                    <th data-translate="expiry_date">失效期</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 库存警告商品表格内容动态生成 -->
                            </tbody>
                        </table>
                    </div>
                    <div id="stockWarningPagination" class="pagination-container mt-3 d-flex justify-content-between">
                        <button id="stockPrevPage" class="btn btn-secondary" data-translate="previous_page">上一页</button>
                        <span id="stockPageInfo" data-translate="page_info">1 页 共 1 页</span>
                        <button id="stockNextPage" class="btn btn-secondary" data-translate="next_page">下一页</button>
                    </div>
                </div>
                
                <!-- 近效期警告界面 -->
                <div id="expiry_warning" class="card-content d-none">
                    <h4 data-translate="expiry_warning">近效期警告</h4>
                    <div class="table-responsive">
                        <table id="expiryWarningTable" class="table table-striped">
                            <thead>
                                <tr>
                                    <th data-translate="product_barcode">商品条码</th>
                                    <th data-translate="product_name">商品名称</th>
                                    <th data-translate="unit_price">单价</th>
                                    <th data-translate="unit">单位</th>
                                    <th data-translate="stock_quantity">库存数量</th>
                                    <th data-translate="expiry_date">失效期</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 近效期警告商品表格内容动态生成 -->
                            </tbody>
                        </table>
                    </div>
                    <div id="expiryWarningPagination" class="pagination-container mt-3">
                        <!-- 分页控件动态生成 -->
                    </div>
                </div>
                
                <!-- 系统设置界面 -->
                <div id="settings" class="card-content d-none">
                    <form id="settingsForm">
                        <div class="form-group text-center" style="width: 100%;">
                            <!-- 隐藏的文件输入元素 -->
                            <input type="file" id="storeLogo" accept="image/jpeg,image/png,image/gif" class="d-none">
                            <!-- 可点击的LOGO预览区域 -->
                            <div style="cursor: pointer; display: inline-block; position: relative;">
                                <img id="logoPreview" src="static/images/logo.jpeg" alt="店铺LOGO" class="img-fluid rounded" style="max-height: 150px; max-width: 150px; border: 2px dashed #ccc;">
                                <!-- 上传状态指示器 -->
                                <div id="uploadStatus" style="display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0,0,0,0.7); color: white; padding: 5px 10px; border-radius: 4px;">上传中...</div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label id="storeZhNameLable" for="storeNameZh" data-translate="storeZhNameLable">店铺汉语名称</label>
                            <input type="text" id="storeNameZh" class="form-control" data-translate="storeZhNameLable" placeholder="请输入店铺汉语名称">
                        </div>
                        <div class="form-group">
                            <label id="storeUyNameLable" for="storeNameUy" data-translate="storeUyNameLable">店铺维吾尔语名称</label>
                            <input type="text" id="storeNameUy" class="form-control" data-translate="storeUyNameLable" placeholder="请输入店铺维吾尔语名称" style="direction: rtl; text-align: right;">
                        </div>
                        <button type="submit" id="confirmChangeBtn" class="btn btn-primary" data-translate="confirmChangeBtn">保存设置</button>
                    </form>
                </div>
            </div>
        </div>
    </div>


    <!-- 密码修改弹窗 -->
    <div id="changePasswordModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content" style="margin-top: 40px;">
                <div class="modal-header">
                    <h5 class="modal-title" id="changePasswordModalLabel">修改密码</h5>
                    <button type="button" class="close" id="closeModalBtn" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="changePasswordForm">
                        <div class="form-group">
                            <label for="currentPassword">原密码</label>
                            <input type="password" class="form-control" id="currentPassword" required>
                        </div>
                        <div class="form-group">
                            <label for="newPassword">新密码</label>
                            <input type="password" class="form-control" id="newPassword" required>
                            <small id="passwordHelp" class="form-text text-muted">密码长度至少4位</small>
                        </div>
                        <div class="form-group">
                            <label for="confirmPassword">确认新密码</label>
                            <input type="password" class="form-control" id="confirmPassword" required>
                        </div>
                        <div class="form-group">
                            <label for="verificationCode">验证码</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="verificationCode" required>
                                <div class="input-group-append">
                                    <button type="button" class="btn btn-secondary" id="generateCode">获取验证码</button>
                                </div>
                            </div>
                            <div id="codeDisplay" class="mt-2 p-2 bg-light text-center font-weight-bold d-none"></div>
                        </div>
                        <button type="submit" class="btn btn-primary">确认修改</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 修改密码相关脚本 -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 验证码生成与显示
            let generatedCode = '';
            const generateCodeBtn = document.getElementById('generateCode');
            const codeDisplay = document.getElementById('codeDisplay');
            
            generateCodeBtn.addEventListener('click', function() {
                // 生成6位随机数字验证码
                generatedCode = Math.floor(100000 + Math.random() * 900000).toString();
                codeDisplay.textContent = generatedCode;
                codeDisplay.classList.remove('d-none');
                
                // 禁用按钮一段时间
                generateCodeBtn.disabled = true;
                generateCodeBtn.textContent = '已生成验证码';
                setTimeout(() => {
                    generateCodeBtn.disabled = false;
                    generateCodeBtn.textContent = '获取验证码';
                    // 30秒后清除验证码
                    if (codeDisplay.textContent === generatedCode) {
                        codeDisplay.classList.add('d-none');
                        generatedCode = '';
                    }
                }, 30000);
            });
            
            // 点击修改密码链接显示弹窗
            const changePasswordLink = document.getElementById('changePasswordLink');
            const changePasswordModal = $('#changePasswordModal');
            const closeModalBtn = document.getElementById('closeModalBtn');
            
            changePasswordLink.addEventListener('click', function(e) {
                e.preventDefault();
                // 关闭下拉菜单
                const dropdownMenu = this.closest('.dropdown-menu');
                if (dropdownMenu) {
                    dropdownMenu.classList.remove('show');
                }
                // 显示弹窗
                changePasswordModal.modal('show');
            });
            
            // 关闭按钮点击事件
            closeModalBtn.addEventListener('click', function() {
                changePasswordModal.modal('hide');
                // 重置表单
                changePasswordForm.reset();
                codeDisplay.classList.add('d-none');
                generatedCode = '';
            });
            
            // 表单提交处理
            const changePasswordForm = document.getElementById('changePasswordForm');
            
            changePasswordForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 获取表单数据
                const currentPassword = document.getElementById('currentPassword').value;
                const newPassword = document.getElementById('newPassword').value;
                const confirmPassword = document.getElementById('confirmPassword').value;
                const verificationCode = document.getElementById('verificationCode').value;
                
                // 验证表单数据
                  if (!currentPassword) {
                      alert('请输入原密码');
                      return;
                  }
                  
                  if (newPassword.length < 4) {
                      alert('新密码长度至少为4位');
                      return;
                  }
                  
                  if (currentPassword === newPassword) {
                      alert('原密码和新密码不能相同');
                      return;
                }
                
                if (newPassword !== confirmPassword) {
                    alert('两次输入的新密码不一致');
                    return;
                }
                
                if (verificationCode !== generatedCode) {
                    alert('验证码不正确');
                    return;
                }
                
                // 创建表单数据对象
                const formData = new FormData();
                formData.append('old_password', currentPassword);
                formData.append('new_password', newPassword);
                formData.append('captcha', verificationCode);
                
                // 发送AJAX请求到服务器修改密码
                fetch('/change_password', {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin'  // 包含cookies
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('密码修改成功，请重新登录');
                        
                        // 关闭弹窗
                        changePasswordModal.modal('hide');
                        
                        // 重置表单
                        changePasswordForm.reset();
                        codeDisplay.classList.add('d-none');
                        generatedCode = '';
                        
                        // 跳转到登录页面
                        setTimeout(() => {
                            window.location.href = '/logout';
                        }, 1000);
                    } else {
                        alert(data.message || '密码修改失败');
                    }
                })
                .catch(error => {
                    console.error('修改密码错误:', error);
                    alert('网络错误，请稍后重试');
                });
            });
        });
    </script>
    
    <!-- 引入模块化JS -->
    <!-- 使用模块加载器自动加载所有模块 -->
    <script src="static/js/module-loader.js"></script>
    <!-- 引入 JsBarcode 库，用于生成商品条码 -->
    <script src="static/js/JsBarcode.all.min.js"></script>
    <!-- 添加交易记录相关功能 -->
    <script>
        // 加载交易记录的函数
        window.loadTransactions = function(page) {
            $.ajax({
                url: `/api/transactions?page=${page}`,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderTransactionTable(response.transactions);
                        renderPagination(response.current_page, response.total_pages, response.total_records);
                    } else {
                        alert('加载交易记录失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('加载交易记录时发生网络错误');
                }
            });
        };
        
        // 渲染交易记录表格
        function renderTransactionTable(transactions) {
            const tableBody = $('#transactionTableBody');
            tableBody.empty();
            
            if (transactions.length === 0) {
                tableBody.append('<tr><td colspan="4" class="text-center">暂无记录</td></tr>');
                return;
            }
            
            transactions.forEach(transaction => {
                // 格式化时间
                const formattedTime = new Date(transaction.transaction_time).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
                
                // 确保使用当前语言的翻译文本
                const trans = window.translations?.[window.currentLang] || {};
                const viewDetailsText = trans.viewDetails || '查看明细';
                const printReceiptText = trans.printReceipt || '打印结算单';
                
                const row = `
                    <tr>
                        <td>${transaction.transaction_no}</td>
                        <td>${formattedTime}</td>
                        <td>¥${parseFloat(transaction.total_amount).toFixed(2)}</td>
                        <td>
                            <button class="btn btn-info btn-sm view-details-btn" onclick="viewTransactionDetails(${transaction.id})">
                                ${viewDetailsText}
                            </button>
                            <button class="btn btn-warning btn-sm ml-1 print-receipt-btn" onclick="showPrintPreview(${transaction.id})">
                                ${printReceiptText}
                            </button>
                        </td>
                    </tr>
                `;
                tableBody.append(row);
            });
        }
        
        // 渲染分页控件
        function renderPagination(currentPage, totalPages, totalRecords) {
            const paginationControls = $('#paginationControls');
            const paginationInfo = $('#paginationInfo');
            paginationControls.empty();
            
            // 获取当前语言的翻译文本
            const currentLang = window.currentLang || 'zh';
            const trans = window.translations?.[currentLang] || {};
            
            // 更新分页信息
            const startRecord = currentPage === 1 ? 1 : (currentPage - 1) * 10 + 1;
            const endRecord = Math.min(currentPage * 10, totalRecords);
            if (trans.paginationInfo) {
                // 使用翻译后的格式
                paginationInfo.text(trans.paginationInfo.replace('1-0', `${startRecord}-${endRecord}`).replace('0', totalRecords));
            } else {
                paginationInfo.text(`显示 ${startRecord}-${endRecord} 条，共 ${totalRecords} 条`);
            }
            
            // 添加上一页按钮
            const prevLi = $('<li class="page-item"></li>');
            const prevText = trans.prevPage || '上一页';
            const prevA = $(`<a class="page-link" href="#">${prevText}</a>`);
            if (currentPage === 1) {
                prevLi.addClass('disabled');
            } else {
                prevA.on('click', function(e) {
                    e.preventDefault();
                    loadTransactions(currentPage - 1);
                });
            }
            prevLi.append(prevA);
            paginationControls.append(prevLi);
            
            // 添加页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageLi = $('<li class="page-item"></li>');
                const pageA = $(`<a class="page-link" href="#">${i}</a>`);
                
                if (i === currentPage) {
                    pageLi.addClass('active');
                } else {
                    pageA.on('click', function(e) {
                        e.preventDefault();
                        loadTransactions(i);
                    });
                }
                
                pageLi.append(pageA);
                paginationControls.append(pageLi);
            }
            
            // 添加下一页按钮
            const nextLi = $('<li class="page-item"></li>');
            const nextText = trans.nextPage || '下一页';
            const nextA = $(`<a class="page-link" href="#">${nextText}</a>`);
            if (currentPage === totalPages) {
                nextLi.addClass('disabled');
            } else {
                nextA.on('click', function(e) {
                    e.preventDefault();
                    loadTransactions(currentPage + 1);
                });
            }
            nextLi.append(nextA);
            paginationControls.append(nextLi);
        }
        
        // 查看交易明细
        window.viewTransactionDetails = function(transactionId) {
            $.ajax({
                url: `/api/transactions/${transactionId}/details`,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        showTransactionDetailsModal(response.transaction, response.details);
                    } else {
                        alert('获取交易明细失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('获取交易明细时发生网络错误');
                }
            });
        };
        
        // 显示交易明细弹窗
        function showTransactionDetailsModal(transaction, details) {
            // 创建弹窗HTML
            const modalHtml = `
                <div class="modal fade" id="transactionDetailsModal" tabindex="-1" role="dialog" aria-labelledby="transactionDetailsModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="transactionDetailsModalLabel">结算明细</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="mb-4">
                                    <p><strong>流水号：</strong>${transaction.transaction_no}</p>
                                    <p><strong>交易时间：</strong>${new Date(transaction.transaction_time).toLocaleString('zh-CN')}</p>
                                    <p><strong>总金额：</strong>¥${parseFloat(transaction.total_amount).toFixed(2)}</p>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead class="thead-dark">
                                            <tr>
                                                <th>商品条码</th>
                                                <th>商品名称</th>
                                                <th>单价</th>
                                                <th>数量</th>
                                                <th>小计</th>
                                            </tr>
                                        </thead>
                                        <tbody id="transactionDetailsTableBody">
                                            ${details.map(detail => `
                                                <tr>
                                                    <td>${detail.barcode}</td>
                                                    <td>${detail.product_name}</td>
                                                    <td>¥${parseFloat(detail.price).toFixed(2)}</td>
                                                    <td>${detail.quantity}</td>
                                                    <td>¥${parseFloat(detail.subtotal).toFixed(2)}</td>
                                                </tr>
                                            `).join('')}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary close-modal">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 移除可能存在的旧弹窗
            $('#transactionDetailsModal').remove();
            
            // 添加新弹窗
            $(document.body).append(modalHtml);
            
            // 显示弹窗
            const modal = $('#transactionDetailsModal');
            
            // 添加CSS样式让弹窗更靠下
            const modalDialog = modal.find('.modal-dialog');
            modalDialog.css({
                'display': 'flex',
                'align-items': 'center',
                'min-height': '80vh',  // 使用视口高度的80%作为最小高度
                'margin-top': '80px'   // 添加顶部边距让弹窗下移
            });
            
            modal.modal('show');
            
            // 为右上角关闭按钮添加点击事件
            modal.find('.close[data-dismiss="modal"]').on('click', function() {
                modal.modal('hide');
            });
            
            // 为底部关闭按钮添加点击事件
            modal.find('.close-modal').on('click', function() {
                modal.modal('hide');
            });
            
            // 弹窗关闭时移除元素
            modal.on('hidden.bs.modal', function() {
                $(this).remove();
            });
        }
        
        // 当DOM加载完成，为结算明细页面添加事件监听
        $(document).ready(function() {
            // 为侧边栏菜单项添加点击事件监听，当切换到结算明细页面时加载数据
            $('a[data-target="settle_detail"]').on('click', function(e) {
                e.preventDefault();
                setTimeout(() => {
                    // 延迟执行以确保页面已切换
                    loadTransactions(1); // 加载第一页数据
                }, 100);
            });
        });
        // 搜索交易记录
        $('#searchTransactionBtn').on('click', function() {
            const transactionNo = $('#transactionNoSearch').val().trim();
            if (transactionNo) {
                searchTransactionsByNo(transactionNo);
            } else {
                loadTransactions(1); // 重置为加载所有记录
            }
        });
        
        // 重置搜索
        $('#resetSearchBtn').on('click', function() {
            $('#transactionNoSearch').val('');
            loadTransactions(1);
        });
        
        // 按回车搜索
        $('#transactionNoSearch').on('keypress', function(e) {
            if (e.which === 13) {
                $('#searchTransactionBtn').click();
            }
        });
        
        // 根据流水号搜索交易记录
        function searchTransactionsByNo(transactionNo) {
            $.ajax({
                url: `/api/transactions?search_no=${transactionNo}`,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderTransactionTable(response.transactions);
                        renderPagination(response.current_page, response.total_pages, response.total_records);
                    } else {
                        alert('搜索失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('搜索时发生网络错误');
                }
            });
        }
        
        // 显示打印预览
        window.showPrintPreview = function(transactionId) {
            console.log('显示打印预览，交易ID:', transactionId);
            $.ajax({
                url: `/api/transactions/${transactionId}/details`,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log('获取交易详情成功:', JSON.stringify(response, null, 2));
                    // 直接渲染预览，即使response没有success字段
                    renderPrintPreview(response);
                    $('#printPreviewModal').modal('show');
                },
                error: function(xhr, status, error) {
                    console.error('获取交易详情时发生网络错误:', error, xhr.responseText);
                    alert('获取交易详情时发生网络错误');
                }
            });
        };
        
        // 渲染打印预览内容
        function renderPrintPreview(responseData) {
            // 添加详细的响应数据日志
            console.log('渲染打印预览，完整响应数据类型:', typeof responseData);
            console.log('渲染打印预览，完整响应:', JSON.stringify(responseData, null, 2));
            
            const previewContent = $('#printPreviewContent');
            previewContent.empty();
            
            // 初始化交易信息和明细数据
            let transaction = {};
            let allDetails = [];
            
            // 尝试从不同结构获取交易数据
            if (responseData && typeof responseData === 'object') {
                // 情况1: responseData是完整的API响应对象
                if (responseData.transaction) {
                    transaction = responseData.transaction;
                    console.log('从responseData.transaction获取交易信息');
                    console.log('交易信息内容:', JSON.stringify(transaction, null, 2));
                } else {
                    // 情况2: responseData本身可能就是交易对象
                    transaction = responseData;
                    console.log('responseData作为交易对象');
                }
                
                // 尝试从多个可能的位置获取明细数据
                // 位置1: responseData.details
                if (Array.isArray(responseData.details)) {
                    allDetails = responseData.details;
                    console.log('从responseData.details获取明细，数量:', allDetails.length);
                }
                // 位置2: transaction.details
                else if (transaction.details && Array.isArray(transaction.details)) {
                    allDetails = transaction.details;
                    console.log('从transaction.details获取明细，数量:', allDetails.length);
                }
                // 位置3: 查找items字段
                else if (Array.isArray(responseData.items)) {
                    allDetails = responseData.items;
                    console.log('从responseData.items获取明细，数量:', allDetails.length);
                }
                // 位置4: 查找transaction.items字段
                else if (transaction.items && Array.isArray(transaction.items)) {
                    allDetails = transaction.items;
                    console.log('从transaction.items获取明细，数量:', allDetails.length);
                }
                // 位置5: 如果明细数据是对象格式，转换为数组
                else if (typeof responseData.details === 'object' && responseData.details !== null && !Array.isArray(responseData.details)) {
                    // 尝试将对象转换为数组格式
                    allDetails = Object.values(responseData.details);
                    console.log('将responseData.details对象转换为数组，数量:', allDetails.length);
                }
                else {
                    // 检查是否是嵌套对象格式的明细
                    const possibleDetailKeys = ['details', 'items', '明细', '商品明细'];
                    for (const key of possibleDetailKeys) {
                        if (responseData[key] && typeof responseData[key] === 'object') {
                            if (Array.isArray(responseData[key])) {
                                allDetails = responseData[key];
                                console.log(`从responseData[${key}]获取明细，数量:`, allDetails.length);
                                break;
                            } else {
                                allDetails = Object.values(responseData[key]);
                                console.log(`将responseData[${key}]对象转换为数组，数量:`, allDetails.length);
                                break;
                            }
                        }
                    }
                    
                    // 如果仍然没有找到，打印详细诊断信息
                    if (allDetails.length === 0) {
                        console.log('未找到有效的明细数据，详细结构分析:');
                        console.log('responseData属性:', Object.keys(responseData));
                        console.log('transaction属性:', Object.keys(transaction));
                        
                        // 检查所有可能的嵌套结构
                        for (const key in responseData) {
                            if (typeof responseData[key] === 'object') {
                                console.log(`responseData[${key}]类型:`, typeof responseData[key], '是数组:', Array.isArray(responseData[key]));
                            }
                        }
                    }
                }
            }
            
            // 格式化时间
            let formattedTime = '未知';
            const timeFields = ['transaction_time', 'time', 'create_time', 'created_at'];
            for (const field of timeFields) {
                if (transaction[field]) {
                    try {
                        formattedTime = new Date(transaction[field]).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        });
                        break;
                    } catch (e) {
                        console.error(`格式化${field}时间出错:`, e);
                    }
                }
            }
            
            // 获取交易号
            let transactionNo = '未知';
            const noFields = ['transaction_no', 'id', 'number', '流水号'];
            for (const field of noFields) {
                if (transaction[field]) {
                    transactionNo = transaction[field];
                    break;
                }
            }
            
            // 获取操作员
            let operator = '系统';
            const operatorFields = ['operator', 'user', 'username', '操作员'];
            for (const field of operatorFields) {
                if (transaction[field]) {
                    operator = transaction[field];
                    break;
                }
            }
            
            // 构建明细表格行
            let detailsHtml = '';
            if (allDetails.length > 0) {
                console.log('开始构建明细表格...');
                detailsHtml = allDetails.map((detail, index) => {
                    // 详细日志记录每个明细项
                    console.log(`明细项 ${index} 原始数据:`, JSON.stringify(detail, null, 2));
                    
                    // 确保detail是对象
                    if (typeof detail === 'object' && detail !== null) {
                        // 尝试多种可能的字段名称获取商品信息
                        const productNameFields = ['product_name', 'name', '商品名称', 'goods_name', 'product'];
                        let productName = '未知商品';
                        for (const field of productNameFields) {
                            if (detail[field]) {
                                productName = detail[field];
                                break;
                            }
                        }
                        
                        // 获取价格
                        const priceFields = ['price', '单价', 'unit_price', 'cost'];
                        let price = 0;
                        for (const field of priceFields) {
                            if (detail[field]) {
                                price = parseFloat(detail[field]) || 0;
                                break;
                            }
                        }
                        
                        // 获取数量
                        const quantityFields = ['quantity', '数量', 'count', 'num'];
                        let quantity = 0;
                        for (const field of quantityFields) {
                            if (detail[field]) {
                                quantity = detail[field];
                                break;
                            }
                        }
                        
                        // 获取金额
                        const subtotalFields = ['subtotal', '金额', 'total', '小计'];
                        let subtotal = 0;
                        for (const field of subtotalFields) {
                            if (detail[field]) {
                                subtotal = parseFloat(detail[field]) || 0;
                                break;
                            }
                        }
                        
                        // 如果没有找到小计，计算价格*数量
                        if (subtotal === 0 && price > 0 && quantity > 0) {
                            subtotal = price * quantity;
                        }
                        
                        console.log(`构建行 ${index}: ${productName}, ¥${price.toFixed(2)}, ${quantity}, ¥${subtotal.toFixed(2)}`);
                        return `
                            <tr>
                                <td>${productName}</td>
                                <td>¥${price.toFixed(2)}</td>
                                <td>${quantity}</td>
                                <td>¥${subtotal.toFixed(2)}</td>
                            </tr>
                        `;
                    }
                    console.log(`明细项 ${index} 无效或不是对象:`, detail);
                    return '';
                }).join('');
                
                // 如果所有明细项都无效，显示特殊提示
                if (!detailsHtml) {
                    detailsHtml = '<tr><td colspan="4" class="text-center">明细数据格式异常</td></tr>';
                    console.log('所有明细项都无效，显示异常提示');
                }
            } else {
                detailsHtml = '<tr><td colspan="4" class="text-center">暂无明细数据</td></tr>';
                console.log('明细数组为空');
            }
            
            // 获取总计金额
            let totalAmount = '0.00';
            const totalFields = ['total_amount', 'amount', '总计', '总价', 'total'];
            for (const field of totalFields) {
                if (transaction[field]) {
                    totalAmount = parseFloat(transaction[field]) || 0;
                    break;
                }
            }
            // 如果没找到总计，尝试从明细计算
            if (totalAmount === '0.00' && allDetails.length > 0) {
                const calculatedTotal = allDetails.reduce((sum, detail) => {
                    if (typeof detail === 'object' && detail !== null) {
                        const subtotalFields = ['subtotal', '金额', 'total', '小计'];
                        for (const field of subtotalFields) {
                            if (detail[field]) {
                                return sum + (parseFloat(detail[field]) || 0);
                            }
                        }
                    }
                    return sum;
                }, 0);
                if (calculatedTotal > 0) {
                    totalAmount = calculatedTotal;
                }
            }
            totalAmount = parseFloat(totalAmount).toFixed(2);
            
            // 创建打印预览内容
            const content = `
                <div class="receipt-container" style="max-width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ccc;">
                    <div class="text-center mb-4">
                        <h3>结算单</h3>
                    </div>
                    <div class="mb-4">
                        <p><strong>流水号:</strong> ${transactionNo}</p>
                        <div class="text-center mb-2" style="margin: 10px 0;">
                            <svg id="transactionBarcode" style="max-width: 100%; height: auto;"></svg>
                        </div>
                        <p><strong>交易时间:</strong> ${formattedTime}</p>
                        <p><strong>操作员:</strong> ${operator}</p>
                    </div>
                    <div class="mb-4">
                        <h4>商品明细</h4>
                        <table class="table table-bordered" style="font-size: 14px;">
                            <thead>
                                <tr>
                                    <th>商品名称</th>
                                    <th>单价</th>
                                    <th>数量</th>
                                    <th>金额</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${detailsHtml}
                            </tbody>
                        </table>
                    </div>
                    <div class="text-right mb-4">
                        <p><strong>总计:</strong> ¥${totalAmount}</p>
                    </div>
                    <div class="text-center">
                        <div id="barcodeContainer" style="margin: 20px 0;"></div>
                         
                    </div>
                </div>
            `;
            
            previewContent.append(content);
            
            // 生成结算单号条码
            try {
                // 确保 JsBarcode 库已加载
                if (typeof JsBarcode !== 'undefined') {
                    // 使用结算单号生成条码（CODE128格式，支持数字和字母）
                    // 如果结算单号不是纯数字，使用CODE128；如果是纯数字，可以使用EAN13或CODE128
                    const barcodeValue = String(transactionNo).trim();
                    if (barcodeValue && barcodeValue !== '未知') {
                        JsBarcode("#transactionBarcode", barcodeValue, {
                            format: "CODE128",  // CODE128格式支持字母和数字
                            width: 2,
                            height: 60,
                            displayValue: true,  // 显示条码下方的文字
                            fontSize: 14,
                            textAlign: "center",
                            textPosition: "bottom",
                            textMargin: 5,
                            margin: 10
                        });
                        console.log('结算单号条码生成成功:', barcodeValue);
                    } else {
                        console.warn('结算单号无效，无法生成条码');
                        $('#transactionBarcode').parent().hide();
                    }
                } else {
                    console.error('JsBarcode 库未加载');
                    $('#transactionBarcode').parent().hide();
                }
            } catch (error) {
                console.error('生成条码时出错:', error);
                $('#transactionBarcode').parent().hide();
            }
            
            // 隐藏旧的条码容器（如果存在）
            const barcodeContainer = $('#barcodeContainer');
            if (barcodeContainer.length) {
                barcodeContainer.hide();
            }
        }
    </script>
    
    <!-- 打印预览模态框 -->
    <div class="modal fade" id="printPreviewModal" tabindex="-1" role="dialog" aria-labelledby="printPreviewModalLabel" style="margin-top: 30px;">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="printPreviewModalLabel">结算单预览</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="printPreviewCloseBtn">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="printPreviewContent">
                        <!-- 打印预览内容将通过JavaScript动态添加 -->
                          <!-- 条形码生成区域 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="printReceipt()">打印</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 打印函数 -->
    <script>
        function printReceipt() {
            // 这里可以实现实际的打印功能
            // alert('打印功能将在这里实现');
            // 实际实现可以使用 window.print()
            window.print("printPreviewContent");
        }
        
        // 为打印预览关闭按钮添加事件处理
        $(document).ready(function() {
            // 为关闭按钮添加点击事件
            $('#printPreviewCloseBtn').on('click', function() {
                // 确保模态框关闭
                $('#printPreviewModal').modal('hide');
                console.log('打印预览关闭按钮被点击');
            });
            
            // 也为底部关闭按钮添加类似处理
            $('#printPreviewModal .modal-footer .btn-secondary').on('click', function() {
                $('#printPreviewModal').modal('hide');
            });
        });
    </script>
</body>
</html>